package mammuthus.web.action

import javax.servlet.http.HttpServletRequest
import mammuthus.web.service.{AsyncHelperTrait, SlaveService}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestParam, RequestMethod, RequestMapping}

import scala.collection.JavaConversions._
import mammuthus.web.bean.{ShellResult, SlaveBean}
import org.slf4j.LoggerFactory
import net.sf.json.{JSONObject, JSONArray}
import net.liftweb.{json => SJSon}
import java.net.URLEncoder

/**
 * Created by fengbingjian on 15/5/3 13:12.
 */
@Controller()
@RequestMapping(Array("docker"))
class DockerAction extends ActionHelperTrait with AsyncHelperTrait with DockerContainerAction{

  val logger = LoggerFactory.getLogger(classOf[DockerAction])
  @Autowired
  val slaveService: SlaveService = null

  @RequestMapping(Array("containers.html"))
  def containers(req: HttpServletRequest,
                 @RequestParam(value = "slaves", defaultValue = "") slaves: String,
                 @RequestParam(value = "status", defaultValue = "all") status: String
                  ) = {
    req.setAttribute("slaves", slaves)
    req.setAttribute("containers", slaveService.containerList(slaves, status))
    req.setAttribute("page", "Containers")

    "dockerIndex"
  }

  @RequestMapping(Array("hosts.html"))
  def hosts(req: HttpServletRequest) = {
    val hosts: java.util.List[SlaveBean] = formatIP(slaveService.getSlave()).filter(f => f.docker.enable)
    req.setAttribute("hosts", hosts)
    req.setAttribute("hostsStr", hosts.map(f => f.getHostName).mkString(","))
    req.setAttribute("guessGatewayIp",if(hosts.size()>0) hosts.map(f => f.ip).reverse.take(1)(0).split("\\.").take(3).mkString(".") + "." else "")
    req.setAttribute("page", "Hosts")

    "dockerHostList"
  }

  @RequestMapping(Array("agents.html"))
  def agents(req: HttpServletRequest) = {
    val hosts: java.util.List[SlaveBean] = slaveService.getSlave()
    req.setAttribute("hosts", hosts)
    req.setAttribute("hostsStr", hosts.map(f => f.getHostName).mkString(","))
    req.setAttribute("guessGatewayIp",if(hosts.size()>0) hosts.map(f => f.ip).reverse.take(1)(0).split("\\.").take(3).mkString(".") + "." else "")
    req.setAttribute("page", "Hosts")

    "dockerHostList"
  }

  @RequestMapping(Array("container/start.html"))
  def startContainer(req: HttpServletRequest,
                     @RequestParam(value = "hostName", defaultValue = "") hostName: String,
                     @RequestParam(value = "id", defaultValue = "") id: String
                      ) = {
    slaveService.startContainer(hostName, id)
    s"redirect:/docker/containers.html?slaves=$hostName"
  }

  @RequestMapping(Array("container/stop.html"))
  def stopContainer(req: HttpServletRequest,
                    @RequestParam(value = "hostName", defaultValue = "") hostName: String,
                    @RequestParam(value = "id", defaultValue = "") id: String
                     ) = {
    slaveService.stopContainer(hostName, id)
    s"redirect:/docker/containers.html?slaves=$hostName"
  }


  @RequestMapping(value = Array("host_network_configure.html"), method = Array(RequestMethod.GET))
  def hostNetworkConfigure(req: HttpServletRequest, @RequestParam(value = "slaves", defaultValue = "") slaves: String) = {
    req.setAttribute("hostStr", slaves)
    "hostNetworkConfigure"
  }


  @RequestMapping(value = Array("host_network_configure.html"), method = Array(RequestMethod.POST))
  def hostNetworkConfigurePOST(req: HttpServletRequest) = {
    val res = slaveService.configureNetwork(encodeFromMapToUrlQuery(req.getParameterMap))

    val isError = try {
      JSONArray.fromObject(res)
      false
    }
    catch {
      case e: Exception => true
    }

    if (isError) {
      req.setAttribute("shellRes", "")
      req.setAttribute("tasks", new JSONArray())
      req.setAttribute("msg",res)
    } else {
      req.setAttribute("shellRes", res)
      req.setAttribute("tasks", toJava(getTaskInfo(slaveService.masterUrl, res)))
      req.setAttribute("msg",JSONArray.fromObject(res).getJSONObject(0).getString("message"))
    }

    "shellCommandExecuteResult"
  }


  @RequestMapping(value = Array("shellProcess.html"), method = Array(RequestMethod.POST))
  def shellProcess(req: HttpServletRequest, @RequestParam(value = "shellRes", defaultValue = "") shellRes: String) = {
    import net.liftweb.{json => SJSon}
    implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)
    val items = getTaskInfo(slaveService.masterUrl, shellRes)
    logger.info(SJSon.Serialization.write(items))
    req.setAttribute("shellRes", shellRes)
    req.setAttribute("tasks", toJava(items))
    "shellCommandExecuteResult"
  }

  @RequestMapping(value = Array("shellProcess2.html"), method = Array(RequestMethod.GET))
  def shellProcess2(req: HttpServletRequest, @RequestParam(value = "shellRes", defaultValue = "") shellRes: String) = {
    req.setAttribute("shellRes", "")
    req.setAttribute("tasks", new JSONArray())
    "shellCommandExecuteResult"
  }


}
